import {asyncAction, asyncActionHandler} from 'shared/utils/actionUtil';
import * as actionTypes from '../consts';
import {goback} from 'shared/actions';
import API from '../api';

export const getDataSources = () => asyncAction({
  type: actionTypes.GET_DATASOURCE,
  payload: API.getDataSources(),
});

export const onDelete = id => asyncAction({
  type: actionTypes.AJAX_STATUS,
  payload: API.delete(id),
  handlers: asyncActionHandler(dispatch => {
    dispatch(getDataSources());
  }),
});


export const initFormStatus = () => asyncAction({
  payload: {body: {}},
  type: actionTypes.FORM_STATUS,
});

export const initFormData = () => asyncAction({
  type: actionTypes.FORM_DATA,
  payload: {body: {}},
  handlers: {success: dispatch => dispatch(initFormStatus())},
});

export const getFormData = id => asyncAction({
  type: actionTypes.FORM_DATA,
  payload: API.getFormData(id),
  handlers: {success: dispatch => dispatch(initFormStatus())},
});

export const temp2redux = formData => asyncAction({
  payload: {body: formData},
  type: actionTypes.TEMP_2_REDUX,
});

export const postForm = (formData, createContinue) => asyncAction({
  payload: API.postForm(formData),
  type: actionTypes.FORM_STATUS,
  handlers: asyncActionHandler((dispatch) => {
    if (createContinue) {
      dispatch(initFormData());
    } else {
      dispatch(goback());
    }
    dispatch(getDataSources());
  }),
});

export const putForm = formData => asyncAction({
  payload: API.putForm(formData),
  type: actionTypes.FORM_STATUS,
  handlers: asyncActionHandler((dispatch) => {
    dispatch(goback());
    dispatch(getDataSources());
  }),
});
